package com.yazi.mxz.job.quartz;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.Page;
import com.yazi.mxz.common.entity.beans.Email;
import com.yazi.mxz.common.entity.enums.EmailStatus;
import com.yazi.mxz.common.entity.enums.EmailType;
import com.yazi.mxz.common.service.EmailService;
import com.yazi.mxz.job.common.MySetting;
import com.yazi.mxz.job.common.tool.EmailFactory;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class EmailJob  extends MyJob {
	private static Logger log = LoggerFactory.getLogger(EmailJob.class);
	/**
	 * 所有邮件类型
	 */
	private static final EmailType[] TYPES = EmailType.values();
	/**
	 * 累计发送失败次数，每次激活任务时重新累计。
	 */
	private static int error = 0;
	/**
	 * 任务状态，是否在执行
	 */
	private static boolean isWorking = false;
	
	@Resource
	EmailService emailService;
	@Resource
	FreeMarkerConfigurer freeMarkerConfigurer;

	@Override
	public void run() {
		if (!MySetting.getMailSwitch()) {
			log.warn("邮件服务未开启");
			return;
		}
		isWorking = true;
		Email emailFs = new Email();
		emailFs.setStatus(EmailStatus.NEW.ordinal());
		emailFs.setAddTime(DateUtil.getTimeStamp() - MySetting.getMailIndate() * 60000);
		Searching search = new Searching();
		search.setPageSize(Searching.MAX_PAGE_SIZE);
		Page<Email> page = emailService.listByGtAddtime(emailFs, search);
		List<Email> list = page.getList();
		String content;// 邮件正文内容
		boolean success = false;// 某个邮件是否发送成功
		for (Email email : list) {
			log.debug("发送邮件：id={},email={},type={}", new Object[]{email.getEmailId(), email.getToEmail(), email.getType()});
			success = true;
			try {
				content = getEmailContent(email.getType(), email.getParams());
				EmailFactory.sendMail(email.getToEmail(), TYPES[email.getType()].getText(), content);
			} catch (Exception e) {
				log.error("邮件发送失败", e);
				email.setFail(email.getFail() + 1);
				if (email.getFail() > 3) { // TODO 等处理，限定尝试发送次数
					// 达到失败次数则取消
					email.setStatus(EmailStatus.CANCEL.ordinal());
				}
				success = false;
				error++;
				// 失败达到限定次数就终止任务
				if (error == MySetting.getMailError()) {
					break;
				}
			}
			if (success) {
				// 更新为“成功”状态
				email.setStatus(EmailStatus.SUCCESS.ordinal());
			}
			email.setSendTime(DateUtil.getTimeStamp());
			emailService.merge(email);
		}
		if (error < MySetting.getMailError() && search.getTotalPage() > search.getNowPage()) {
			 run();
			return;
		}
		isWorking = false;
		return;
	}

	@Override
	public void checkDoit(long timeStamp) {
		if (isWorking) return;
		error = 0;
		doit();
	}
	
	public void checkDoit() {
		checkDoit(0);
	}
	
	private String getEmailContent(int type, String params) throws IOException, TemplateException {
		Configuration cfg = freeMarkerConfigurer.getConfiguration();
		Template template = cfg.getTemplate("email_" + type + ".ftl");
		template.setEncoding(cfg.getDefaultEncoding());
		StringWriter writer = new StringWriter();
		Map<String, Object> rootMap = new HashMap<String, Object>();
		String[] paramArray = params.split("\\|\\&\\|", -1);// |&|
		rootMap.put("params", paramArray);
		template.process(rootMap, writer);
		return writer.toString();
	}
}
